package org.csu.mall.controller;


import org.csu.mall.common.CONSTANT;
import org.csu.mall.common.UniformResponse;
import org.csu.mall.entity.Cart;
import org.csu.mall.service.Impl.CartServiceImpl;
import org.csu.mall.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/cart/")
public class CartController {
    @Autowired
    CartServiceImpl cartService;

    @PostMapping("add_cart")
    @ResponseBody
    public UniformResponse<CartVO> addCart(Integer productId,
                                           @RequestParam(name="quantity",defaultValue = "1") Integer quantity,
                                         HttpSession session)
    {
        UniformResponse response =cartService.addCart(productId, quantity);
        if (response.isSuccess()) {
            session.setAttribute(CONSTANT.ADDCART, response.getData());
        }
        return response;
    }

    @PostMapping("update_cart")
    @ResponseBody
    public UniformResponse<CartVO> updateCart(Integer quantity,
                                              Integer productId,
                                              HttpSession session){
        UniformResponse response =cartService.updateCart(quantity, productId);
        if (response.isSuccess()) {
            session.setAttribute(CONSTANT.UPDATECART, response.getData());
        }
        return response;
    }

    @PostMapping("delete_cart")
    @ResponseBody
    public UniformResponse<CartVO> deleteCart(Integer productId,HttpSession session)
    {
        UniformResponse response =cartService.deleteCart(productId);
        if (response.isSuccess()) {
            session.setAttribute(CONSTANT.DELETECART, response.getData());
        }
        return response;
    }

    @PostMapping("delete_many_cart")
    @ResponseBody
    public UniformResponse<CartVO> deleteManyCartItems(HttpSession session){
        UniformResponse response =cartService.deleteManyCartItems();
        if (response.isSuccess()) {
            session.setAttribute(CONSTANT.DELETEMANYCART, response.getData());
        }
        return response;
    }

    @GetMapping("list")
    @ResponseBody
    public UniformResponse<CartVO> getCartList(HttpSession session)
    {
        UniformResponse<CartVO> response=cartService.getCartList();
        if(response.isSuccess())
        {
            session.setAttribute(CONSTANT.CARTITEMLIST,response.getData());
        }
        return response;
    }

}
